package com.tedu.excelinportdamo.service;

import com.tedu.excelinportdamo.mapper.NodeMapper;
import com.tedu.excelinportdamo.pojo.dto.NodeDTO;
import com.tedu.excelinportdamo.pojo.entity.Node;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Iterator;

@Service
@Slf4j
public class NodeService {

    @Autowired
    private NodeMapper nodeMapper;
    public void importExcelData(InputStream inputStream) throws Exception{
        try (Workbook workbook=new XSSFWorkbook(inputStream)){
            log.info("开始导入Excel文件数据");
            Sheet sheet=workbook.getSheetAt(0);
            Iterator<Row> rowIterator=sheet.iterator();
            rowIterator.next();// 跳过表头行
            while (rowIterator.hasNext()){
                Row row=rowIterator.next();
                // 读取每一行数据，并保存到数据库中
                Iterator<Cell> cellIterator=row.cellIterator();
                Node node=new Node();
                // 读取每一列数据 根据列索引读取数据对应数据库中的字段
                node.setName(cellIterator.next().getStringCellValue());
                node.setIpAddress(cellIterator.next().getStringCellValue());
                node.setType(cellIterator.next().getStringCellValue());
                node.setManufacturer(cellIterator.next().getStringCellValue());
                node.setModel(cellIterator.next().getStringCellValue());
                log.debug("正在导入数据："+node);
                nodeMapper.insertNode(node);
            }
            log.info("Excel文件数据导入完成");
            //workbook.close();
            //inputStream.close();

        }
    }

    public Object selectNodeList(NodeDTO nodeDTO){
        return nodeMapper.selectNodeList(nodeDTO);
    }

}
